package com.qianfeng.smsplatform.strategy.service.impl;//
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//                  佛祖镇楼                  BUG辟易
//          佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//


import com.qianfeng.smsplatform.common.constants.CacheConstants;
import com.qianfeng.smsplatform.common.constants.RabbitMqConsants;
import com.qianfeng.smsplatform.common.constants.StrategyConstants;
import com.qianfeng.smsplatform.common.model.Standard_Report;
import com.qianfeng.smsplatform.common.model.Standard_Submit;
import com.qianfeng.smsplatform.strategy.feign.RedisCacheFeign;
import com.qianfeng.smsplatform.strategy.mq.SendMq;
import com.qianfeng.smsplatform.strategy.service.FilterChain;
import com.qianfeng.smsplatform.strategy.service.ReportMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.Set;

/**
 * Created by Mr.ycz on 2019/12/3 9:43
 */
public class SmsOpIDFilter implements FilterChain {
    private final static Logger log = LoggerFactory.getLogger(SmsBlackFilter.class);

    @Autowired
    private RedisCacheFeign cacheFeign;
    @Autowired
    private SendMq sendMq;

    @Value("${sms_send_limit.day}")
    private int day;
    @Value("${sms_send_limit.hour}")
    private int hour;
    @Value("${sms_send_limit.five_minute}")
    private int fiveMinutes;


    @Override
    public boolean dealMessage(Standard_Submit submit) {
        //发送之前查询缓存 前缀+客户id+用户电话+短信内容+“*”  “*”-->匹配时间戳

        //5分钟限流
        Set<String> keys = cacheFeign.keys(CacheConstants.CACHE_PREFIX_SMS_LIMIT_FIVE_MINUTE +
                                                  submit.getClientID() + ":" +
                                                  submit.getDestMobile() + ":" +
                                                  submit.getMessageContent() + "*");
        int secondCount=0;
        if (keys != null) {
            secondCount = keys.size();
        }


        if (secondCount < fiveMinutes) {
            //存入缓存
            cacheFeign.setString(CacheConstants.CACHE_PREFIX_SMS_LIMIT_FIVE_MINUTE +
                                     submit.getClientID() + ":" +
                                     submit.getDestMobile() + ":" +
                                     submit.getMessageContent() + ":" +
                                     new Date().getTime(), "1", 300);
        } else {
            //发送相同短信超过3条  限制其发送短信
            log.error("5分钟内客户id===>{}发送相同短信超过3条，已被禁止",submit.getClientID());
            sendMq.sendMq(RabbitMqConsants.TOPIC_SMS_SEND_LOG, submit);

            if (submit.getSource() != null && "1".equals(submit.getSource())) {
                //发送模拟报告
                Standard_Report report = ReportMsg.sendReport(submit);
                report.setErrorCode(StrategyConstants.STRATEGY_ERROR_LIMIT);
                report.setState(2);
                log.info("限流发送状态报告====>{}",report);
                sendMq.sendMq(RabbitMqConsants.TOPIC_PUSH_SMS_REPORT, report);
            }
            return false;
        }


        //1小时限流5条相同
        Set<String> keysHour = cacheFeign.keys(CacheConstants.CACHE_PREFIX_SMS_LIMIT_HOUR +
                                                      submit.getClientID() + ":" +
                                                      submit.getDestMobile() + ":" +
                                                      submit.getMessageContent() + "*");
        int hourCount =0;
        if (keysHour != null) {
            hourCount = keysHour.size();
        }

        if (hourCount < hour) {
            //存入缓存
            cacheFeign.setString(CacheConstants.CACHE_PREFIX_SMS_LIMIT_HOUR +
                                     submit.getClientID() + ":" +
                                     submit.getDestMobile() + ":" +
                                     submit.getMessageContent() + ":" +
                                     new Date().getTime(), "1", 60 * 60);
        } else {
            //发送相同短信超过3条  限制其发送短信
            log.error("一个小时内客户id  {}发送相同短信超过5条，已被禁止",submit.getClientID());
            sendMq.sendMq(RabbitMqConsants.TOPIC_SMS_SEND_LOG, submit);

            if (submit.getSource() != null && "1".equals(submit.getSource())) {

                Standard_Report report = ReportMsg.sendReport(submit);
                report.setState(2);
                report.setErrorCode(StrategyConstants.STRATEGY_ERROR_LIMIT);
                log.info("发送状态报告====>{}",report);
                sendMq.sendMq(RabbitMqConsants.TOPIC_PUSH_SMS_REPORT, report);
            }
            return false;
        }


        //一天限流  10条
        Set<String> keysDay = cacheFeign.keys(CacheConstants.CACHE_PREFIX_SMS_LIMIT_DAY +
                                                     submit.getClientID() + ":" +
                                                     submit.getDestMobile() + ":" +
                                                     submit.getMessageContent() + "*");
        int dayCount =0;
        if (keysDay != null) {
            dayCount = keysDay.size();
        }

        if (dayCount < day) {
            //存入缓存
            cacheFeign.setString(CacheConstants.CACHE_PREFIX_SMS_LIMIT_DAY +
                                     submit.getClientID() + ":" +
                                     submit.getDestMobile() + ":" +
                                     submit.getMessageContent() + ":" +
                                     new Date().getTime(), "1", 60 * 60 * 24);
        } else {
            //发送相同短信超过10条  限制其发送短信
            log.error("一天内客户id   {}发送相同短信超过10条，已被禁止",submit.getClientID());
            sendMq.sendMq(RabbitMqConsants.TOPIC_SMS_SEND_LOG, submit);

            if (submit.getSource() != null && "1".equals(submit.getSource())) {
                Standard_Report report = ReportMsg.sendReport(submit);
                report.setState(2);
                report.setErrorCode(StrategyConstants.STRATEGY_ERROR_LIMIT);
                log.info("限流发送状态报告====>{}",report);

                sendMq.sendMq(RabbitMqConsants.TOPIC_PUSH_SMS_REPORT, report);
            }
            return false;
        }

        return true;
    }
}
